<template>
  <a-modal
    :visible="visible"
    title="学期管理"
    cancelText="取消"
    okText="保存"
    width="60%"
    @ok="submit"
    @cancel="cancel"
  >
    <a-form
      ref="formRef"
      :model="modelForm.data"
      :rules="formRules"
      :label-col="{ span: 8 }"
      :wrapperCol="{ span: 22 }"
    >
      <a-row>
        <a-col :span="12">
          <a-form-item label="学年" name="semesterName">
            <a-date-picker
              style="width: 100px"
              v-model:value="modelForm.data.beginDate"
              mode="year"
              inputReadOnly
              placeholder="开始"
              format="YYYY"
              @focus="startFocus"
              :open="formState.openDateStart"
              @panelChange="panelChangeStart"
            />
            <a-date-picker
              style="width: 100px"
              v-model:value="modelForm.data.endDate"
              mode="year"
              inputReadOnly
              placeholder="结束"
              format="YYYY"
              @focus="endFocus"
              :open="formState.openDateEnd"
              @panelChange="panelChangeEnd"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="季度" name="quarter">
            <a-select
              v-model:value="modelForm.data.quarter"
              :placeholder="t('placeholder.pleaseSelect')"
            >
              <a-select-option
                v-for="(item, index) in dictLists.data[
                  dictEnum.QUARTER
                ]"
                :key="index"
                :value="item.value"
              >
                {{ item.label || "" }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-modal>
</template>
<script>
import { message, Form } from "ant-design-vue";
import { save, details, update } from "@/api/module/term-manage";
import { defineComponent, reactive, ref, toRaw, onMounted, computed, watch } from "vue";
import dictEnum from "@/const/dict";
import { getDictByCodesReturnObj } from "@/tools/get-dict";
import { useI18n } from "vue-i18n";
import moment from "moment";
const useForm = Form.useForm;
export default defineComponent({
  props: {
    visible: {
      type: Boolean,
    },
    itemId: [String, Number],
  },
  emit: ["close"],
  setup(props, context) {
    const formRef = ref();
    const { t } = useI18n();

    const formState = reactive({
      name: "",
      openDateStart: false,
      openDateEnd: false,
    });
    const dictLists = reactive({
      data: {}
    })
    const modelForm = reactive({
      data: {
        semesterName: "",
        quarter: "",
        beginDate: '',
        endDate: '',
      },
    });
    const semesterName = computed(() => {
      const { beginDate, endDate } = modelForm.data
      let result = null
      if (beginDate && endDate) {
        result =  moment(beginDate).format('YYYY') + '-' + moment(endDate).format('YYYY')
      }
      return result
    })
    const formRules = {
      semesterName: [
        { required: true, validator: (rules, value) => {
          modelForm.data.semesterName = semesterName.value
          if (modelForm.data.semesterName) {
            return Promise.resolve();
          }
          return Promise.reject('请选择学年');
        }, trigger: "change" },
      ],
      quarter: [
        { required: true, message: "请选择季度", trigger: "change" },
      ],
    };
    const { resetFields, validate, validateInfos } = useForm(
      modelForm.data,
      formRules
    );
    const submit = () => {
      formRef.value.validate().then(() => {
        const result = modelForm.data;
        result.semesterName = semesterName.value
        if (result.id) {
          update(result)
            .then((res) => {
              if (res.success) {
                cancel();
                message.success({ content: "修改成功", duration: 1 });
              } else {
                message.warning({ content: "修改失败", duration: 1 });
              }
            })
            .catch((err) => {
              console.log("err: ", err);
            });
        } else {
          save(result)
            .then((res) => {
              if (res.success) {
                cancel();
                message.success({ content: "保存成功", duration: 1 });
              } else {
                message.warning({ content: "保存失败", duration: 1 });
              }
            })
            .catch((err) => {
              console.log("err: ", err);
            });
        }
      });
    };

    const cancel = () => {
      context.emit("close", "visibleSave");
    };
    const getDetails = () => {
      const id = props.itemId || "";
      if (!id) return;
      return details({ id })
        .then((result) => {
          if (result.success) {
            modelForm.data = reactive({ ...result.data });
            modelForm.data.beginDate = modelForm.data.beginDate
                                      ? moment(modelForm.data.beginDate).format('YYYY-MM-DD')
                                      : ''
            modelForm.data.endDate = modelForm.data.endDate
                                      ? moment(modelForm.data.endDate).format('YYYY-MM-DD')
                                      : ''
          }
        })
        .catch((err) => {
          console.log("err: ", err);
        });
    };
    getDetails();
    const panelChangeStart = (value, model) => {
      modelForm.data.beginDate = moment(value._d).format('YYYY-MM-DD')
      console.log('modelForm.data.beginDate: ', modelForm.data.beginDate);
      formState.openDateStart = false
    };
    const panelChangeEnd = (value, model) => {
      modelForm.data.endDate = moment(value._d).format('YYYY-MM-DD')
      formState.openDateEnd = false
    };
    
    const startFocus = (value, model) => {
      formState.openDateStart = true
    };
    const endFocus = (value, model) => {
      formState.openDateEnd = true
    };

    onMounted(async () => {
      dictLists.data = await getDictByCodesReturnObj([
        dictEnum.SEM_YEAR, // 年份
        dictEnum.QUARTER, // 季度
      ]);
    })
    return {
      submit,
      cancel,
      formRef,
      resetFields,
      validateInfos,
      formState,
      modelForm,
      formRules,
      t,
      dictLists,
      dictEnum,
      panelChangeStart,
      panelChangeEnd,
      startFocus,
      endFocus,
    };
  },
});
</script>
